package cn.jhoncy.jproject.framework.security;

import cn.jhoncy.jproject.framework.dto.Customer;
import cn.jhoncy.jproject.system.entity.SysRole;
import cn.jhoncy.jproject.system.entity.SysUser;
import cn.jhoncy.jproject.system.entity.SysUserRole;
import cn.jhoncy.jproject.system.mapper.SysRoleMapper;
import cn.jhoncy.jproject.system.mapper.SysUserMapper;
import cn.jhoncy.jproject.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 重写UserDetailsService 用以设置Security用户信息
 * Created by zhuangqi on 17-4-17.
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;


    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        SysUser q = new SysUser();
        q.setUsername(userName);
        //取得用户
        SysUser user = sysUserMapper.selectOne(q);
        if (user == null){
            throw new UsernameNotFoundException("UserName " + userName + " not found");
        }
        //取得用户权限
        Collection<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);
        return new Customer(user,true,true,true,true, (Set<GrantedAuthority>) grantedAuths);
    }

    public Set<GrantedAuthority> obtionGrantedAuthorities(SysUser sysUser) {
        //获取用户角色
        SysUserRole q = new SysUserRole();
        q.setUserId(sysUser.getUserId());
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.select(q);
        List<String> userRoleIds = new ArrayList<String>();
        for (SysUserRole userRole : sysUserRoles){
            userRoleIds.add(userRole.getRoleId());
        }
        //获取用户角色
        List<SysRole> roles = sysRoleMapper.selectByIds(userRoleIds.toString());
        //提供当前用户(UserDetails)所获得的系统范围内的授权
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
        for (SysRole r : roles){
            authSet.add(new SimpleGrantedAuthority(r.getRoleName()));
        }
        return authSet;
    }
}
